package com.franklin.maven.localcleaner.threadpool;

import com.intellij.ide.AppLifecycleListener;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nullable;

import java.util.Objects;
import java.util.concurrent.*;

/**
 * 线程池配置
 * @author: Ye Junhui
 * @since : 2022/4/7 0007
 */
public class ThreadPool implements AppLifecycleListener {

    private static volatile ExecutorService executorService;

    public static ExecutorService getExecutorService() {
        return executorService;
    }

    @Override
    public void appStarted() {
        //dcl
        if (Objects.isNull(executorService)){
            synchronized (ThreadPool.class){
                if (Objects.isNull(executorService)){
                    int availableProcessors = Runtime.getRuntime().availableProcessors();
                    int min = availableProcessors;
                    if (min < 2){
                        min = 2;
                    }
                    executorService = new ThreadPoolExecutor(
                            min,
                            availableProcessors,
                            60000L,
                            TimeUnit.MILLISECONDS,
                            new LinkedBlockingQueue<>(2000),
                            Executors.defaultThreadFactory(),
                            new ThreadPoolExecutor.CallerRunsPolicy()
                    );
                }
            }
        }
    }

    @Override
    public void appClosing() {
        synchronized (ThreadPool.class){
            if (Objects.nonNull(executorService)){
                executorService.shutdown();
            }
        }
    }
}
